package com.lvhx.rocketmq;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

@RocketMQTransactionListener
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            // 1. 解析消息
            String orderId = msg.getHeaders().get("order_id", String.class);
            // 2. 执行本地事务（如数据库操作）
            boolean success = true;
            // 3. 返回事务状态
            return success ? RocketMQLocalTransactionState.COMMIT :
                    RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.UNKNOWN; // 触发回查
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 回查逻辑（如查询数据库确认事务状态）
//        String orderId = parseOrderIdFromMsg(msg);
        boolean isSuccess = true;
        return isSuccess ? RocketMQLocalTransactionState.COMMIT :
                RocketMQLocalTransactionState.ROLLBACK;
    }

}